﻿using Elasticsearch.Synchronize.Common.Enum;
using ES.Client;

namespace Elasticsearch.Synchronize.Client
{
    public class StorageContainer
    {
        private string GetFilter(DataSource dataSource, long uid)
        {
            var filter = string.Empty;
            switch (dataSource)
            {
                case DataSource.HexinDbEventJoin:
                    filter = string.Format("{EventId:{0}}", uid);
                    break;
                case DataSource.ScarmDbContactsContact:
                    filter = string.Format("{ScrmCompanyId:{0}}", uid);
                    break;
                default:
                    break;
            }

            return filter;
        }

        public DataProvider GetProvider(DataSource dataSource, long uid)
        {
            try
            {
                string filter = this.GetFilter(dataSource, uid);
                ElasticHub<SynchronizeConfig> hub = new ElasticHub<SynchronizeConfig>();
                var parameter = hub.NewParameter();
                parameter.Must.EQ(t => t.JsonFilter, filter)
                    .EQ(t => t.Enabled, true)
                    .EQ(t => t.State, (int)SyncState.Tail);
                var response = hub.Count(parameter);
                if (response.IsValid && response.Count > 0)
                {
                    return DataProvider.ElasticSearch;
                }

                return DataProvider.MongoDB;
            }
            catch
            {
                return DataProvider.MongoDB;
            }
        }
    }
}